
class MyPromise {
    // 定义状态值
    pending = 'pending';
    fulfilled = 'fulfilled';
    rejected = 'rejected';
  
    constructor(callback){
      // 初始化状态，值
      this.status = this.pending;
      this.value = undefined;
      this.reason = undefined;
  
      this.onResolvedCallback = [];
      this.onRejectedCallback = [];
  
      // resolve方法
      const resolve = (value) => {
        if(this.status === this.pending){
          this.status = this.fulfilled;
          this.value = value;
          this.onResolvedCallback.forEach(cb => cb())
        }
      };
      // reject方法
      const reject = (reason) => {
        if(this.status === this.pending){
          this.status = this.rejected;
          this.reason = reason;
          this.onRejectedCallback.forEach(cb => cb())
        }
      };
      // 立即执行执行器函数
      try{
        callback(resolve, reject)
      }catch(err){
        reject(err)
      }
    }
  
    then(onResolved, onRejected){
      // then 函数参数类型必须为函数
      onResolved = typeof onResolved === 'function' ? onResolved : (value) => value;
      onRejected = typeof onRejected === 'function' ? onRejected : (err) => {throw err};
      const newPromise = new MyPromise((resolve, reject) => {
        // 当前promise状态为fufilled
        if(this.status === this.fulfilled){
          try{
            const v = onResolved(this.value);
            resolve(v)
          }catch(err){
            reject(err)
          }
        }
        // 当前promise状态为rejected
        if(this.status === this.rejected){
          try{
            const r = onRejected(this.reason);
            reject(r)
          }catch(err){
            reject(err)
          }
        }
        // 当前状态为pending
        if(this.status === this.pending){
          // 将onResolved，onRejected值保存起来，等待异步完成之后执行
          this.onResolvedCallback.push(() => {
            try{
              const v = onResolved(this.value);
              resolve(v)
            }catch(err){
              reject(err)
            }
          })
  
          this.onRejectedCallback.push(() => {
            try{
              const r = onRejected(this.reason);
              reject(r)
            }catch(err){
              reject(err)
            }
          })
        } else {
          // 清空
          this.onResolvedCallback = [];
          this.onRejectedCallback = [];
        }
      })
      return newPromise;
    }
    catch(onRejected){
      return this.then(null, onRejected)
    }
    // 静态方法resolve
    static resolve(value){
      if(value instanceof MyPromise){
        return value
      }
      return new MyPromise((resolve, reject) => {
        resolve(value)
      })
    }
  
    // 静态方法catch
    static reject(reason){
      return new MyPromise((resolve, reject) => {
        reject(reason)
      })
    }
  }